package com.example.thread;

public class EnergySystem {

    private final double[] energyBos;
    private final Object lock = new Object();

    public EnergySystem(int n, double initialEnergy) {
        this.energyBos = new double[n];
        for (int i = 0; i < energyBos.length; i++) {
            energyBos[i] = initialEnergy;
        }
    }

    public void transfer(int form, int to, double num) {
        synchronized (lock) {
            while (energyBos[form] < num) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.printf("从%d转到%d",form,to);
            energyBos[form] -= num;
            energyBos[to] += num;
            System.out.printf("从%10.2f转移%10.2f到%10.2f中", energyBos[form], num, energyBos[to]);
            System.out.printf("能量总和:%10.2f%n", getTotalEnergy());
//            lock.notifyAll();
        }
    }

    private double getTotalEnergy() {
        double totle = 0;
        for (double amout : energyBos) {
            totle += amout;
        }
        return totle;
    }

    public int getBoxSize() {
        return energyBos.length;
    }
}
